<?php
namespace App\Admin\Forms;

use Dcat\Admin\Models\Administrator;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Dcat\Admin\Contracts\LazyRenderable;
use App\Models\Device;
use Illuminate\Support\Facades\Log;

class ResetUser extends Form implements LazyRenderable
{
    use LazyWidget; // 使用异步加载功能
    protected $title = '修改用户';
    // 处理请求

    public function handle(array $input)
    {
        $id = $this->payload['id'] ?? null;
        //$id = request()->input('id');
        // 根据设备ID查找对应的设备模型
        $device = Device::query()->find($id);
        //DD($device);
       
        if ($device) {
            // Get previous user before any updates
            $previousUser = $device->User_id;
            $previousUserName = '';
            
            if (!empty($previousUser)) {
                $previousAdministrator = Administrator::where('name', $previousUser)->first();
                if ($previousAdministrator) {
                    $previousUserName = $previousAdministrator->name;
                }
            }

            // Get new user info
            $newUser = request()->input('User_id');
            $newUserName = '';
            
            if (!empty($newUser)) {
                $newAdministrator = Administrator::where('name', $newUser)->first();
                if ($newAdministrator) {
                    $newUserName = $newAdministrator->name;
                }
            }

            // Log the change
            $Asset_Number = $device->Asset_Number;
            $date = date('Y-m-d');
            $reason = request()->input('更换原因');
            Log::info("更换用户操作 ---> 日期:[{$date}] -- 资产编号：[{$Asset_Number}] 用户由：{$previousUserName} 更换为：{$newUserName} -- 更换原因:{$reason}");
            
            // Update the device after logging
            $device->User_id = $newUser;
            $device->State = empty($newUser) ? '空闲' : '正常';
            $device->save();
            
            return $this->response()->success('设备用户更新成功')->refresh('Dcat.reload()');
        }
        // 返回错误的消息
        return $this->response()->error('设备用户更新失败');
   
    }
    public function form()
    {
        $users = Administrator::pluck('name', 'name');
        $this->select('User_id')
            ->options(array_merge(['' => '空'], $users->toArray()));
            
        $this->text('更换原因')->required();
        //$user = request('User');
        //$reason = request('更换原因');
        
        //Log::debug('用户:'.$user.' - 更换原因:'.$reason);

        
    }
}